define(['app', 'js/directive/listTree', 'js/filter/tree2Arr', 'datetime', 'pagination', 'autocomplete', 'floatlayer'], function(app) {
    'use strict';
    /*manage knowledgeproperty*/
    app.controller('OrderCustomer', function($scope, crmConst, dataFactoryCRM, $q, $compile, $timeout, $rootScope, $http, $routeParams) {
        $scope.firstparam = {};
        $scope.secondparam = {};
        $scope.addsecondparam = { adduser: [], add: [] };
        $scope.editsecondparam = {};
        $scope.editthirdparam = {};
        $scope.thirdparam = {};
        $scope.param = {};
        $scope.userpackage = {};
        $scope.sign = { customer: 1, user: 10, stranger: 20 };
        $scope.stratorend = { start: 1, end: 0 };
        $scope.editcallsubcompany = new Array();
        $scope.packagearr = new Array();
        $scope.checkedall = false;
        $scope.type = 1;
        $scope.open = [{ k: '-1', v: '全部' }, { k: '0', v: '未开通' }, { k: '1', v: '已开通' }];
        $scope.order = [{ k: '-1', v: '全部' }, { k: '0', v: '未关注' }, { k: '1', v: '已关注' }];
        $scope.forbidden = [{ k: '-1', v: '全部' }, { k: '0', v: '未禁用' }, { k: '1', v: '已禁用' }];
        $scope.qysourcepage = {
            pageAll: 1,
            pageNow: 1,
            pageSize: $scope.psize,
            // pageSize: 2,
            k: 3892
        };



        // OrderCustomer list
        $scope.OrderCustomerDataList = function(key) {
            $scope.type = key;
            // alert($scope.type);
            if ($scope.type == 1) {
                $scope.firstactive = 'item active';
                $scope.secondactive = 'item';
                $scope.thirdactive = 'item';
                $scope.firstsegment = 'ui bottom attached tab segment active';
                $scope.secondsegment = 'ui bottom attached tab segment';
                $scope.thirdsegment = 'ui bottom attached tab segment';
            } else if ($scope.type == 10) {
                $scope.secondactive = 'item active';
                $scope.firstactive = 'item';
                $scope.thirdactive = 'item';
                $scope.secondsegment = 'ui bottom attached tab segment active';
                $scope.firstsegment = 'ui bottom attached tab segment';
                $scope.thirdsegment = 'ui bottom attached tab segment';
            } else {
                $scope.thirdactive = 'item active';
                $scope.firstactive = 'item';
                $scope.secondactive = 'item';
                $scope.thirdsegment = 'ui bottom attached tab segment active';
                $scope.firstsegment = 'ui bottom attached tab segment';
                $scope.secondsegment = 'ui bottom attached tab segment';
            }
            var qyparam;
            var url = 'OrderCustomer/Index';
            if (key == 1) {
                if ($scope.firstparam.package) {
                    $rootScope.go('/ordercustomer');
                    url += '?' + $.param($scope.firstparam) + '&packagecode=' + '';
                } else {
                    if ($routeParams.package_code != undefined) {
                        url += '?' + $.param($scope.firstparam) + '&packagecode=' + $routeParams.package_code;
                    } else {
                        url += '?' + $.param($scope.firstparam) + '&packagecode=' + '';
                    }
                }
            } else if (key == 10) {
                if ($scope.secondparam.package) {
                    url += '?' + $.param($scope.secondparam) + '&packagecode=' + '';
                } else {
                    if ($routeParams.package_code != undefined) {
                        url += '?' + $.param($scope.secondparam) + '&packagecode=' + $routeParams.package_code;
                    } else {
                        url += '?' + $.param($scope.secondparam) + '&packagecode=' + '';
                    }
                }
            } else {
                if ($scope.thirdparam.package) {
                    url += '?' + $.param($scope.thirdparam) + '&packagecode=' + '';
                } else {
                    if ($routeParams.package_code != undefined) {
                        url += '?' + $.param($scope.thirdparam) + '&packagecode=' + $routeParams.package_code;
                    } else {
                        url += '?' + $.param($scope.thirdparam) + '&packagecode=' + '';
                    }
                }
            }
            dataFactoryCRM.getDataByAPI(url + '&key=' + key + '&psize=' + $scope.qysourcepage.pageSize + '&p=' + $scope.qysourcepage.pageNow).then(function(d) {
                if (d.subscribe) {
                    if ($scope.type == 1) {
                        $timeout(function() {
                            $('#firstdropdown').dropdown('set selected', d.subscribe);
                        }, 100);
                    } else if ($scope.type == 10) {
                        $timeout(function() {
                            $('#seconddropdown').dropdown('set selected', d.subscribe);
                        }, 100);
                    } else {
                        $timeout(function() {
                            $('#thirddropdown').dropdown('set selected', d.subscribe);
                        }, 100);
                    }
                }
                if (d.package) {
                    if ($scope.type == 1) {
                        $timeout(function() {
                            $('#firstpackagedropdown').dropdown('set selected', d.package);
                        }, 100);
                    } else if ($scope.type == 10) {
                        $timeout(function() {
                            $('#secondpackagedropdown').dropdown('set selected', d.package);
                        }, 100);
                    } else {
                        $timeout(function() {
                            $('#thirdpackagedropdown').dropdown('set selected', d.package);
                        }, 100);
                    }
                }
                if (d.rcode) {
                    $scope.qysourcepage.pageSize = d.psize;
                    $scope.qysourcepage.pageAll = d.pall;
                    $scope.qysourcepage.pageNow = d.p;
                    $scope.qysource = d.data;

                } else {
                    $scope.qysource = {};
                    $scope.qysourcepage.pageAll = 0;
                }
            });
        }

        // page paging
        $scope.pagedisplay = function() {
            $scope.OrderCustomerDataList($scope.type);
        }

        //特殊处理semantic dropdown的反向绑定缺陷 firsttab
        $scope.$watch('firstparam.is_open', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='firstparam.is_open']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('firstparam.is_order', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='firstparam.is_order']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('firstparam.is_forbidden', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='firstparam.is_forbidden']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('firstparam.package', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='firstparam.package']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('firstparam.subscribe', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='firstparam.subscribe']").dropdown('set selected', newValue);
            });
        }, true);

        // second tab
        $scope.$watch('secondparam.is_open', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='secondparam.is_open']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('secondparam.is_order', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='secondparam.is_order']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('secondparam.is_forbidden', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='secondparam.is_forbidden']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('secondparam.package', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='secondparam.package']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('secondparam.subscribe', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='secondparam.subscribe']").dropdown('set selected', newValue);
            });
        }, true);

        // third tab
        $scope.$watch('thirdparam.is_open', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='thirdparam.is_open']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('thirdparam.is_order', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='thirdparam.is_order']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('thirdparam.is_forbidden', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='thirdparam.is_forbidden']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('thirdparam.package', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='thirdparam.package']").dropdown('set selected', newValue);
            });
        }, true);
        $scope.$watch('thirdparam.subscribe', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='thirdparam.subscribe']").dropdown('set selected', newValue);
            });
        }, true);


        //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function() {
            $scope.OrderCustomerDataList($scope.type);
        });


        // get account of company
        $scope.CompanyAccount = function() {
            dataFactoryCRM.getDataByAPI('OrderCustomer/GetCompanyAccount').then(function(d) {
                if (d.rcode) {
                    $scope.companyaccountsearch = d.data;
                    $scope.companyaccount = d.redata;
                }
            });
        }

        $scope.CompanyAccount();

        // watch second tab company account
        $scope.$watch('addsecondparam.companyaccount', function(nv, ov) {
            if ($scope.addsecondparam.companyaccount) {
                $('#addmultipleaddpck').dropdown('clear');
                $scope.GetPackageInModel($scope.addsecondparam.companyaccount).then(function(d) {
                    if (d) {
                        $scope.package = d;
                    }
                });
            }
        });


        //watch third tab company account
        $scope.$watch('thirdparam.companyaccount', function(nv, ov) {
            if ($scope.thirdparam.companyaccount) {
                $timeout(function() {
                    $('#thirdmultiple').dropdown('clear');
                    $scope.GetPackageInModel($scope.thirdparam.companyaccount).then(function(d) {
                        if (d) {
                            $scope.thirdpackage = d;
                        }
                    });
                }, 50);
            }
        });

        // get package in add model
        $scope.GetPackageInModel = function(d) {
            var deferred = $q.defer();
            dataFactoryCRM.postDataByAPI('OrderCustomer/GetPackage', { package: d }).then(function(d) {
                if (d.rcode) {
                    deferred.resolve(d.res);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // get package 
        $scope.GetPackage = function(d) {
            dataFactoryCRM.getDataByAPI('OrderCustomer/GetPackage').then(function(d) {
                if (d.rcode) {
                    $scope.packagesearch = d.data;
                    $scope.package = d.res;
                }
            });
        }

        $scope.GetPackage();

        //get user of the sector
        $scope.getuser = function(_d) {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('OrderCustomer/GetUser?sector_id=' + _d).then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // get subcompany 
        $scope.subcompany = function() {
            dataFactoryCRM.getDataByAPI('OrderCustomer/getsubcompany').then(function(d) {
                if (d.rcode) {
                    $scope.editcallsubcompany = d.data;
                } else {
                    $scope.editcallsubcompany = [];
                }
            });
        }

        $scope.subcompany();

        // watch user of sector
        $scope.$watch('addsecondparam.sector', function(newvalue, oldvalue) {
            if (newvalue != oldvalue) {
                function init() {
                    $scope.checkedall = false;
                    $("input[name='checkedall']").prop('checked', false);
                    $("input[name='add[]']").each(function() { $(this).prop('checked', false); });
                    $scope.addsecondparam.adduser.length = 0;
                    $scope.addsecondparam.add.length = 0;
                    $scope.userpackage = {};
                }
                init();
                $scope.getuser($scope.addsecondparam.sector).then(function(d) {
                    if (d.rcode) {
                        $scope.userpackage = d.data;
                    } else {
                        $scope.userpackage = {};
                    }
                });
            }
        });


        // checkbox users were added
        $scope.addusermsg = function(index) {
            if ($scope.checkedall) {
                $("input[name='checkedall']").prop('checked', false);
                $scope.checkedall = false;
            }
            var user = $scope.userpackage[index];
            var addverify = $scope.addsecondparam.adduser.indexOf(user.login_name);
            if (addverify === -1) {
                $scope.addsecondparam.adduser.push(user.login_name);
                $scope.addsecondparam.add.push(user.nickname);
            } else {
                $scope.addsecondparam.adduser.splice(addverify, 1);
                $scope.addsecondparam.add.splice(addverify, 1);
            }
        }

        //checkbox  checked all
        $scope.checkall = function() {
            if ($scope.checkedall) {
                $scope.checkedall = false;
            } else {
                $scope.checkedall = true;
            }
            $scope.addsecondparam.adduser.length = 0;
            $scope.addsecondparam.add.length = 0;
            if ($scope.checkedall) {
                $("input[name='add[]']").each(function() {
                    $(this).prop('checked', true);
                });
                for (var $i = 0; $i < $scope.userpackage.length; $i++) {
                    $scope.addsecondparam.adduser.push($scope.userpackage[$i].login_name);
                    $scope.addsecondparam.add.push($scope.userpackage[$i].nickname);
                }
            } else {
                $("input[name='add[]']").each(function() {
                    $(this).prop('checked', false);
                    $scope.addsecondparam.adduser.length = 0;
                    $scope.addsecondparam.add.length = 0;
                });
            }
        }

        // add user
        $scope.adduser = function() {
            function addSuccess() {
                $timeout(function() {
                    $('.modal1').modal('show');
                    //3s后关闭
                    $timeout(function() {
                        $('.modal1').modal('hide')
                    }, 3000)
                }, 1000);
            }
            /**添加失败 */
            function addFail() {
                //添加失败了,
                $timeout(function() {
                    $('.modal2').modal('show');
                    //3s后关闭
                    $timeout(function() {
                        $('.modal2').modal('hide')
                    }, 3000)
                }, 1000);
            }

            // display repeating user
            function repeatingUser() {
                $timeout(function() {
                    $('.modal4').modal({
                        onApprove: function() {
                            return true;
                        }
                    }).modal('show');
                }, 4000)
            }


            function init() {
                $timeout(function() { //cause $apply only can be run once time in time , so add $time avoide this case happend
                    $('#adduserform').form('clear');
                    $scope.addsecondparam.adduser.length = 0;
                    $scope.addsecondparam.add.length = 0;
                    $scope.userpackage.length = 0;
                    $scope.addsecondparam.sector = '';
                    $('#adddiv').removeClass('ui basic red pointing prompt label transition visible');
                    $('#adddiv').html('');
                }, 100)

            }
            init();
            $('.ui.add').modal({
                autofocus: false,
                onApprove: function() {
                    if ($('#adduserform').form('is valid')) {
                        dataFactoryCRM.postDataByAPI('OrderCustomer/AddUser', { addsecondparam: $scope.addsecondparam }).then(function(d) {
                            if (d.rcode) {
                                $timeout(function() {
                                    addSuccess();
                                    if (d.nickname) {
                                        $('#subscriber_repeat .content p').html("订户【" + d.nickname + "】添加重复");
                                        repeatingUser();
                                    }
                                    $scope.OrderCustomerDataList($scope.type);
                                }, 200)
                            } else {
                                addFail();
                            }

                        });
                    } else {
                        return false;
                    }
                    if ($scope.addsecondparam.adduser.length == 0) {
                        $('#adddiv').addClass('ui basic red pointing prompt label transition visible');
                        document.getElementById("adddiv").innerHTML = '请选择客户';
                        return false;
                    } else {
                        if ($('#adddiv').hasClass('ui basic red pointing prompt label transition visible')) {
                            $('#adddiv').removeClass('ui basic red pointing prompt label transition visible');
                            document.getElementById("adddiv").innerHTML = '';
                        }
                    }
                }
            }).modal('show');
        }

        // subscriber forbidden
        $scope.qyforbidden = function(k, v, m, n) {
            if (m == 1) {
                $('#subscriber_forbidden .content p').html("订户【姓名:" + n + "】确认禁用吗？");
                $('.forbidden').modal({
                    onApprove: function() {
                        dataFactoryCRM.postDataByAPI('OrderCustomer/SubscriberForbidden', { key: k, val: v }).then(function(d) {
                            $scope.OrderCustomerDataList($scope.type);
                        });
                    }
                }).modal('show');
            } else {
                dataFactoryCRM.postDataByAPI('OrderCustomer/SubscriberForbidden', { key: k, val: v }).then(function(d) {
                    $scope.OrderCustomerDataList($scope.type);
                });
            }
        }

        // delete qysubscriber
        $scope.qydelete = function(k, v) {
            $('#subscriber_del .content p').html("记录【姓名:" + v + "】确认删除吗？");
            $('.modal3').modal({
                onApprove: function() {
                    dataFactoryCRM.postDataByAPI('OrderCustomer/SubscriberDelete', { key: k }).then(function(d) {
                        $scope.OrderCustomerDataList($scope.type, '');
                    });
                }
            }).modal('show');
        }

        // get msg of subscribers
        $scope.getsubscribermsg = function(k) {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('OrderCustomer/ModifyUser?id=' + k).then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // get msg of customer
        $scope.getcustomermsg = function(k) {
            var deferred = $q.defer();
            dataFactoryCRM.getDataByAPI('OrderCustomer/ModifyCustomer?id=' + k).then(function(d) {
                if (d.rcode == 1) {
                    deferred.resolve(d);
                } else {
                    deferred.reject('call function error');
                }
            });
            return deferred.promise;
        }

        // modify qy_user
        $scope.qymodify = function(key) {
            $timeout(function() {
                $('#edituserform').form('clear');
                $timeout(function() {
                    $('#editmultiple').dropdown('restore defaults');
                    $scope.getsubscribermsg(key).then(function(d) {
                        $('#edituserform').form('set values', {
                            usereditwechat: d.data.qy_subscriber_weixinid,
                            usereditphone: d.data.qy_subscriber_mobile,
                        });
                        $scope.editsecondparam = d.data;
                        $scope.addpackage = d.qy_code;
                        $('#userid').val(d.data.qy_subscriber_id);
                        $('#usercompanyaccount').val(d.data.qy_code);
                        if (d.deparment_id) {
                            $scope.editsecondparam.subscribe = d.deparment_id;
                        }
                    });
                    $timeout(function() {
                        if ($scope.editsecondparam.subscribe) {
                            $('#editmultiple').dropdown('set selected', $scope.editsecondparam.subscribe);
                        }
                    }, 100);
                })
            }, 50)

            $('.ui.modify.modal').modal({
                onApprove: function() {
                    if ($('#edituserform').form('is valid')) {
                        dataFactoryCRM.postDataByAPI('OrderCustomer/ModifyUser', { editparam: $scope.editsecondparam }).then(function(d) {
                            if (d.rcode) {
                                $(".ui.small.modal.editOk").modal('show');
                                $timeout(function() {
                                    $('.ui.small.modal.editOk').modal('hide')
                                }, 3000);
                                $scope.OrderCustomerDataList($scope.type, '');
                            } else {
                                $(".ui.modal.editFail").modal('show');
                                $timeout(function() {
                                    $('.ui.modal.editFail').modal('hide')
                                }, 3000);
                            }

                        });
                    } else {
                        return false;
                    }
                }
            }).modal('show');
        }

        // add qy_stranger
        $scope.addstranger = function() {
            function addSuccess() {
                $timeout(function() {
                    $('.modal1').modal('show');
                    //3s后关闭
                    $timeout(function() {
                        $('.modal1').modal('hide')
                    }, 3000)
                }, 1000);
            }
            /**添加失败 */
            function addFail() {
                //添加失败了,
                $timeout(function() {
                    $('.modal2').modal('show');
                    //3s后关闭
                    $timeout(function() {
                        $('.modal2').modal('hide')
                    }, 3000)
                }, 1000);
            }

            function init() {
                $timeout(function() {
                    // $scope.$digest(
                    $('#addstrangerform').form('clear');
                    // );
                }, 50);
            }
            init();
            $('.ui.addstranger').modal({
                autofocus: false,
                onApprove: function() {
                    if ($('#addstrangerform').form('is valid')) {
                        dataFactoryCRM.postDataByAPI('OrderCustomer/AddStranger', { thirdparam: $scope.thirdparam }).then(function(d) {
                            if (d.rcode == 1) {
                                $timeout(function() {
                                    addSuccess();
                                    $scope.OrderCustomerDataList($scope.type, '');
                                }, 200)
                            } else {
                                addFail();
                            }
                        });
                    } else {
                        return false;
                    }
                }
            }).modal('show');
        }

        // modify qy_stranger
        $scope.qystrangermodify = function(key) {
            $timeout(function() {
                $('#editstrangerform').form('clear');
                $timeout(function() {
                    $('#editthirdmultiple').dropdown('restore defaults');
                    $scope.getsubscribermsg(key).then(function(d) {
                        $('#editstrangerform').form('set values', {
                            editstrangername: d.data.qy_subscriber_name,
                            editstrangerwechat: d.data.qy_subscriber_weixinid,
                            editstrangerphone: d.data.qy_subscriber_mobile,
                        });
                        $scope.editthirdparam = d.data;
                        $scope.addthirdpackage = d.qy_code;
                        $('#strangerid').val(d.data.qy_subscriber_id);
                        $('#strangerqycode').val(d.data.qy_code);
                        if (d.deparment_id) {
                            $scope.editthirdparam.subscribe = d.deparment_id;
                        }
                    });
                    $timeout(function() {
                        if ($scope.editthirdparam.subscribe) {
                            $('#editthirdmultiple').dropdown('set selected', $scope.editthirdparam.subscribe);
                        }
                    }, 100);
                })

            }, 50)
            $('.ui.thirdmodify.modal').modal({
                onApprove: function() {
                    if ($('#editstrangerform').form('is valid')) {
                        dataFactoryCRM.postDataByAPI('OrderCustomer/ModifyStranger', { editparam: $scope.editthirdparam }).then(function(d) {
                            if (d.rcode) {
                                $(".ui.small.modal.editOk").modal('show');
                                $timeout(function() {
                                    $('.ui.small.modal.editOk').modal('hide')
                                }, 3000);
                                $scope.OrderCustomerDataList($scope.type, '');
                            } else {
                                $(".ui.modal.editFail").modal('show');
                                $timeout(function() {
                                    $('.ui.modal.editFail').modal('hide')
                                }, 3000);
                            }
                        });
                    } else {
                        return false;
                    }
                }
            }).modal('show');
        }

        // modify customer
        $scope.qycustomermodify = function(key) {
            $timeout(function() {
                $('#editcustomerform').form('reset');
                $timeout(function() {
                    $scope.getcustomermsg(key).then(function(d) {
                        $('#editcustomerform').form('set values', {
                            editwechat: d.data.qy_subscriber_weixinid,
                            editphone: d.data.qy_subscriber_mobile,
                        });
                        $scope.editfirstparam = d.data;
                        $scope.editfirstparam.pro = d.pro;
                        $('#subscriberid').val(d.data.qy_subscriber_id);
                        $('#cst_companyaccount').val(d.data.qy_code);
                    });
                })
            })
            $('.ui.firstmodify.modal').modal({
                onApprove: function() {
                    if ($('#editcustomerform').form('is valid')) {
                        dataFactoryCRM.postDataByAPI('OrderCustomer/ModifyCustomer', { editparam: $scope.editfirstparam }).then(function(d) {
                            if (d.rcode) {
                                $(".ui.small.modal.editOk").modal('show');
                                $timeout(function() {
                                    $('.ui.small.modal.editOk').modal('hide')
                                }, 3000);
                                $scope.OrderCustomerDataList($scope.type, '');
                            } else {
                                $(".ui.modal.editFail").modal('show');
                                $timeout(function() {
                                    $('.ui.modal.editFail').modal('hide')
                                }, 3000);
                            }
                        });
                    } else {
                        return false;
                    }
                }
            }).modal('show');
        }
    })
});